using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlTypes;
using Spring.Data;
using Spring.Data.Generic;
using Spring.Data.Common;
using Spring.Data.Objects.Generic;
using Spring.Transaction;
using Spring.Transaction.Support;

namespace MySearch
{
    public static class AppConfigurer
    {
        //Configuration data from initialization 
        private static AdoTemplate _AdoTemplate;
        private static IPlatformTransactionManager _TransactionManager;

        //Configuraiton data from 
        private static String _ServerName = String.Empty;

        //Configuration data from table app_config
        private static IDictionary<string, IList<string>> _DicKeys = null;

        static AppConfigurer()
        {
            _ServerName = System.Environment.MachineName;
        }
       
        public static void Config(AdoTemplate template)
        {
            _AdoTemplate = template;
            _TransactionManager = new Spring.Data.Core.AdoPlatformTransactionManager(_AdoTemplate.DbProvider);

        }

        #region properties
        public static AdoTemplate AdoTemplate
        {
            get
            {
                if (_AdoTemplate == null)
                    throw new Exception("Component not initialized");

                return _AdoTemplate;
            }
        }

        public static IPlatformTransactionManager TransactionManager
        {
            get
            {
                if (AppConfigurer._TransactionManager == null)
                    throw new InvalidOperationException("Component not initialized!");

                return _TransactionManager;
            }
        }

        public static ITransactionDefinition TransactionDefinition
        {
            get
            {
                if (AppConfigurer._TransactionManager == null)
                    throw new InvalidOperationException("Component not initialized!");

                DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                def.PropagationBehavior = TransactionPropagation.Required;

                return def;
            }
        }

        public static string DateFormat
        {
            get
            {
                return "yyyy-MM-dd";
            }
        }

        public static string DateTimeFormat
        {
            get
            {
                return "yyyy-MM-dd HH:mm:ss";
            }
        }

        public static string NA
        {
            get { return "N/A"; }
        }

        public static string SystemUserID
        {
            get { return "System"; }
        }

        public static string ServerName
        {
            get
            {
                return _ServerName;
            }
        }

        public static string AppName
        {
            get
            {
                return "KDC_Ticket";
            }
        }

        public static string TicketDataSeparator
        {
            get { return "$%#"; }
        }
        #endregion

        #region static methods

        public static IList<string> GetConfig(string key)
        {
            if (!_DicKeys.ContainsKey(key))
                return new List<string>();// throw new InvalidOperationException("Invalid key");

            return _DicKeys[key];
        }

        public static void RefreshConfig()
        {
            string strSql = "select config_key, config_value from app_config "
                + " order by config_key, config_value ";

            IDictionary<string, IList<string>> dic = new Dictionary<string, IList<string>>();
            foreach (string strT in _DicKeys.Keys)
                dic.Add(strT, new List<string>());

            _AdoTemplate.QueryWithRowCallbackDelegate(CommandType.Text, strSql, delegate(IDataReader dr)
            {

                string strKey = dr.GetString(0);
                string strVal = dr.GetString(1);

                if (dic.ContainsKey(strKey))
                    dic[strKey].Add(strVal);
            });

            _DicKeys = dic;
        }

        public static void SaveConfig(string key, string value)
        {
            //Parameters used in check and insert statement
            IDbParameters p = _AdoTemplate.CreateDbParameters();
            p.Add("k", DbType.String).Value = key;
            p.Add("v", DbType.String).Value = value;

            //Check data exists
            string strChk = "select count(*) from app_config  where config_key=@k and config_value=@v ";
            int nFlag = Int32.Parse(_AdoTemplate.ExecuteScalar(CommandType.Text, strChk, p).ToString());
            if (nFlag > 0)
                throw new InvalidOperationException("Configuration already exists");

            //Save to database
            string strIns = "insert into app_config values(@k, @v)";
            _AdoTemplate.ExecuteNonQuery(CommandType.Text, strIns, p);
        }

        public static void RemoveConfig(string key, string value)
        {
            string strDel = "delete from app_config where config_key=@k and config_value=@v ";

            IDbParameters p = _AdoTemplate.CreateDbParameters();
            p.Add("k", DbType.String).Value = key;
            p.Add("v", DbType.String).Value = value;

            _AdoTemplate.ExecuteNonQuery(CommandType.Text, strDel, p);
        }

        #endregion
    }
}


